import "package:flutter/material.dart";
import "package:myapp/_common/geyTextPainter.dart";

class RichTextFoldWidget extends StatelessWidget {
  final String content; //内容
  final int maxLines; //最大行数
  final double maxWidth; //最大宽度
  final TextStyle textStyle; //文本样式
  final int reservedSpace; //预留空间
  final TextSpan? end; //末尾内容
  const RichTextFoldWidget({
    super.key,
    required this.content,
    required this.maxLines,
    required this.maxWidth,
    required this.textStyle,
    this.reservedSpace = 0,
    this.end,
  });
  @override
  Widget build(BuildContext context) {
    String showStr = ''; //待显示内容
    final textPainer = getTextPainter(
      context,
      text: content,
      maxLines: maxLines,
      style: textStyle,
      maxWidth: maxWidth,
    );
    final moreText = textPainer.didExceedMaxLines; //是否超出限制行
    if (moreText) {
      final textSize = textPainer.size; //容器的宽高信息
      final position = textPainer
          .getPositionForOffset(Offset(double.infinity, textSize.height));
      final endOffset = position.offset - 3; //为按钮预留空间
      showStr = content.substring(0, endOffset);
    }
    return moreText? RichText(
      text: TextSpan(
        children: [
          TextSpan(
            text: showStr,
            style: textStyle,
          ),
          TextSpan(
            text: '…',
            style: textStyle,
          ),
          end ?? const TextSpan(),
        ],
      ),
    ) : Text(content,style: textStyle,);
  }
}
